<template>
  <div class="excel-import">
    <!-- 导入按钮 -->
    <el-button 
      type="primary" 
      class="idoo-details-add" 
      @click="openImportDialog"
      :loading="importing"
    >
      <el-icon><Upload /></el-icon>
      {{ importing ? '导入中...' : 'EXCEL导入' }}
    </el-button>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetDialog"
    >
      <div class="import-content">
        <!-- 步骤指示器 -->
        <el-steps :active="currentStep" align-center class="step-indicator">
          <el-step title="下载模板"></el-step>
          <el-step title="上传文件"></el-step>
          <el-step title="导入完成"></el-step>
        </el-steps>

        <!-- 步骤1: 下载模板 -->
        <div v-if="currentStep === 0" class="step-content">
          <div class="template-info">
            <el-icon class="info-icon"><InfoFilled /></el-icon>
            <div class="info-text">
              <h4>请先下载导入模板</h4>
              <p>模板包含了必要的列格式和示例数据，请按照模板格式填写数据</p>
            </div>
          </div>
          <div class="template-actions">
            <el-button type="primary" @click="downloadTemplate" :loading="downloading">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
            <el-button @click="currentStep = 1">
              跳过，直接上传
            </el-button>
          </div>
        </div>

        <!-- 步骤2: 上传文件 -->
        <div v-if="currentStep === 1" class="step-content">
          <el-upload
            ref="uploadRef"
            class="upload-dragger"
            drag
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :before-upload="beforeUpload"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :on-progress="onUploadProgress"
            :on-change="onFileChange"
            :auto-upload="false"
            :show-file-list="false"
            :multiple="false"
            accept=".xlsx,.xls"
          >
            <div class="upload-content">
              <el-icon class="el-icon--upload" size="50"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将Excel文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip">
                支持.xlsx、.xls格式，文件大小不超过10MB
              </div>
            </div>
          </el-upload>

          <!-- 文件信息显示 -->
          <div v-if="uploadFile" class="file-info">
            <div class="file-item">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ uploadFile.name }}</span>
              <span class="file-size">({{ formatFileSize(uploadFile.size) }})</span>
              <el-button type="text" @click="removeFile" class="remove-btn">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 调试信息显示 -->
          <div class="debug-info" style="margin: 10px 0; padding: 10px; background: #f0f0f0; border-radius: 4px; font-size: 12px;">
            <p><strong>调试信息:</strong></p>
            <p>uploadFile状态: {{ uploadFile ? '✅ 已选择' : '❌ 未选择' }}</p>
            <p v-if="uploadFile">文件名: {{ uploadFile.name }}</p>
            <p v-if="uploadFile">文件类型: {{ uploadFile.type }}</p>
            <p v-if="uploadFile">文件大小: {{ (uploadFile.size / 1024 / 1024).toFixed(2) }}MB</p>
          </div>

          <!-- 上传进度 -->
          <div v-if="uploadProgress > 0" class="upload-progress">
            <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
          </div>

          <!-- 操作按钮 -->
          <div class="upload-actions">
            <el-button @click="currentStep = 0">上一步</el-button>
            <el-button 
              type="primary" 
              @click="startUpload" 
              :loading="uploading"
              :disabled="!uploadFile"
            >
              开始导入
            </el-button>
          </div>
        </div>

        <!-- 步骤3: 导入结果 -->
        <div v-if="currentStep === 2" class="step-content">
          <div class="result-content">
            <div v-if="importResult.success" class="success-result">
              <el-icon class="result-icon success"><SuccessFilled /></el-icon>
              <h4>导入成功！</h4>
              <p>成功导入 {{ importResult.successSize }} 条数据</p>
              <div v-if="importResult.errorSize > 0" class="warning-info">
                <p>失败 {{ importResult.errorSize }} 条，<el-button type="text" @click="showErrorDetails">查看详情</el-button></p>
              </div>
            </div>
            <div v-else class="error-result">
              <el-icon class="result-icon error"><CircleCloseFilled /></el-icon>
              <h4>导入失败</h4>
              <p>{{ importResult.message || '文件格式错误或数据异常' }}</p>
              <el-button type="text" @click="showErrorDetails">查看详情</el-button>
            </div>
          </div>

          <div class="result-actions">
            <el-button @click="resetImport">重新导入</el-button>
            <el-button type="primary" @click="closeDialog">完成</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 错误详情对话框 -->
    <el-dialog
      v-model="errorDialogVisible"
      title="导入错误详情"
      width="800px"
    >
    <div>
      {{ importResult.errormsg }}
    </div>
      <!-- <el-table :data="importResult.errors" border style="width: 100%">
        <el-table-column prop="row" label="行号" width="80"></el-table-column>
        <el-table-column prop="field" label="字段" width="120"></el-table-column>
        <el-table-column prop="value" label="值" width="150"></el-table-column>
        <el-table-column prop="message" label="错误信息"></el-table-column>
      </el-table> -->
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, 
  Download, 
  UploadFilled, 
  Document, 
  Close, 
  InfoFilled,
  SuccessFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'

export default {
  name: 'ExcelImport',
  components: {
    Upload,
    Download,
    UploadFilled,
    Document,
    Close,
    InfoFilled,
    SuccessFilled,
    CircleCloseFilled
  },
  props: {
    // 导入配置
    importConfig: {
      type: Object,
      required: true,
      default: () => ({
        entityName: '', // 实体名称，对应@TableName
        templateName: '', // 模板名称
        columns: [], // 列配置
        uploadUrl: '', // 上传接口地址
        templateUrl: '' // 模板下载地址
      })
    },
    // 额外的上传数据
    extraData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['import-success', 'import-error'],
  setup(props, { emit }) {
    // 对话框状态
    const dialogVisible = ref(false)
    const errorDialogVisible = ref(false)
    const currentStep = ref(0)
    
    // 上传状态
    const uploading = ref(false)
    const importing = ref(false)
    const downloading = ref(false)
    const uploadProgress = ref(0)
    const uploadStatus = ref('')
    
    // 文件相关
    const uploadRef = ref()
    const uploadFile = ref(null)
    
    // 导入结果
    const importResult = ref({
      success: false,
      successSize: 0,
      errorSize: 0,
      errors: [],
      message: '',
      errormsg :''
    })

    // 计算属性
    const dialogTitle = computed(() => {
      const titles = ['下载导入模板', '上传Excel文件', '导入结果']
      return `${'Excel'} - ${titles[currentStep.value]}`
    })

    const uploadAction = computed(() => {
      return props.importConfig.uploadUrl || '/api/generic-excel-processing/import-file-entity'
    })

    const uploadHeaders = computed(() => {
      return {
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    const uploadData = computed(() => {
      return {
        targetModelName: props.importConfig.entityName,
        ...props.extraData
      }
    })

    // 方法
    const openImportDialog = () => {
      console.log('=== 打开导入对话框 ===')
      console.log('importConfig:', props.importConfig)
      console.log('extraData:', props.extraData)
      
      dialogVisible.value = true
      currentStep.value = 0
    }

    const closeDialog = () => {
      dialogVisible.value = false
      resetDialog()
    }

    const resetDialog = () => {
      currentStep.value = 0
      uploadFile.value = null
      uploadProgress.value = 0
      uploadStatus.value = ''
      uploading.value = false
      importing.value = false
      importResult.value = {
        success: false,
        successSize: 0,
        errorSize: 0,
        errors: [],
        message: ''
      }
    }

    const downloadTemplate = async () => {
      console.log("=== 开始下载模板 ===")
      console.log("当前props:", props)
      console.log("实体名称:", props.importConfig.entityName)
      console.log("模板名称:", props.importConfig.templateName)
      
      downloading.value = true
      try {
        // 动态导入API模块
        const { downloadTemplate: apiDownloadTemplate } = await import('@/api/excelImport.js')
        
        console.log("调用API下载模板...")
        const blob = await apiDownloadTemplate(props.importConfig.entityName)
        
        console.log("=== 模板下载成功 ===")
        console.log("Blob对象:", blob)
        console.log("Blob大小:", blob.size)
        console.log("Blob类型:", blob.type)
        
        // 验证blob是否有效
        if (!blob || !(blob instanceof Blob) || blob.size === 0) {
          throw new Error('下载的文件无效或为空')
        }
        
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${props.importConfig.templateName || '导入模板'}.xlsx`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        
        console.log("✅ 模板文件下载完成")
        ElMessage.success('模板下载成功')
        currentStep.value = 1
      } catch (error) {
        console.error('=== 下载模板失败 ===')
        console.error('错误对象:', error)
        console.error('错误消息:', error.message)
        console.error('错误堆栈:', error.stack)
        
        ElMessage.error(`模板下载失败: ${error.message || '未知错误'}`)
      } finally {
        downloading.value = false
      }
    }

    const beforeUpload = (file) => {
      console.log('=== 文件上传调试信息 ===')
      console.log('选择的文件:', file)
      console.log('文件名:', file.name)
      console.log('文件类型:', file.type)
      console.log('文件大小:', file.size, '字节')
      
      // 更完善的Excel文件类型检查
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel' ||
                     file.name.toLowerCase().endsWith('.xlsx') ||
                     file.name.toLowerCase().endsWith('.xls')
      
      console.log('文件类型检查结果:', isExcel)
      
      if (!isExcel) {
        console.error('文件类型不支持:', file.type)
        ElMessage.error('只能上传Excel文件(.xlsx, .xls)!')
        return false
      }

      const isLt10M = file.size / 1024 / 1024 < 10
      console.log('文件大小检查结果:', isLt10M, '文件大小:', (file.size / 1024 / 1024).toFixed(2), 'MB')
      
      if (!isLt10M) {
        console.error('文件太大:', file.size)
        ElMessage.error('文件大小不能超过10MB!')
        return false
      }

      console.log('文件验证通过，设置uploadFile')
      uploadFile.value = file
      console.log('uploadFile设置完成:', uploadFile.value)
      
      return true // 阻止自动上传
    }

    const startUpload = () => {
      console.log('=== 开始上传流程 ===')
      console.log('当前uploadFile:', uploadFile.value)
      
      if (!uploadFile.value) {
        console.error('❌ 没有选择文件')
        ElMessage.warning('请选择要上传的文件')
        return
      }
      
      console.log('✅ 文件已选择，准备上传')
      console.log('文件信息:', {
        name: uploadFile.value.name,
        size: uploadFile.value.size,
        type: uploadFile.value.type
      })
      
      console.log('上传配置:')
      console.log('- uploadAction:', uploadAction.value)
      console.log('- uploadHeaders:', uploadHeaders.value)
      console.log('- uploadData:', uploadData.value)
      console.log('- uploadRef:', uploadRef.value)
      
      // 验证必要配置
      if (!uploadAction.value) {
        console.error('❌ 上传地址未配置')
        ElMessage.error('上传配置错误：缺少上传地址')
        return
      }
      
      if (!props.importConfig.entityName) {
        console.error('❌ 实体名称未配置')
        ElMessage.error('上传配置错误：缺少实体名称')
        return
      }
      
      uploading.value = true
      importing.value = true
      
      console.log('🚀 调用uploadRef.submit()开始上传')
      try {
        uploadRef.value.submit()
      } catch (error) {
        console.error('❌ 调用submit失败:', error)
        uploading.value = false
        importing.value = false
        ElMessage.error('上传启动失败：' + error.message)
      }
    }

    const onUploadProgress = (event, file) => {
      const progress = Math.round((event.loaded / event.total) * 100)
      console.log('=== 上传进度 ===')
      console.log('上传进度:', progress + '%')
      console.log('已上传:', event.loaded, '总大小:', event.total)
      
      uploadProgress.value = progress
      if (uploadProgress.value < 100) {
        uploadStatus.value = ''
      }
    }

    const onUploadSuccess = (response, file) => {
      console.log('=== 上传成功回调 ===')
      console.log('响应数据:', response)
      console.log('上传文件:', file)
      
      uploading.value = false
      importing.value = false
      uploadProgress.value = 100
      uploadStatus.value = 'success'
      
      if (response && response.success) {
        console.log('✅ 导入成功')
        console.log('成功数量:', response.data?.successSize || 0)
        console.log('失败数量:', response.data?.errorSize || 0)
        
        importResult.value = {
          success: true,
          successSize: response.data?.successSize || 0,
          errorSize: response.data?.errorSize || 0,
          errors: response.data?.errors || [],
          message: response.message,
          errormsg: response.data?.errorExcelDetailsMsg || ''
        }
        emit('import-success', response.data)
        ElMessage.success('导入完成')
      } else {
        console.log('❌ 导入失败')
        console.log('错误信息:', response?.message || '未知错误')
        
        importResult.value = {
          success: false,
          successSize: 0,
          errorSize: 0,
          errors: response?.errors || [],
          message: response?.message || '导入失败'
        }
        emit('import-error', response)
      }
      
      console.log('切换到结果页面')
      currentStep.value = 2
    }

    const onUploadError = (error, file) => {
      console.log('=== 上传错误回调 ===')
      console.error('错误对象:', error)
      console.log('上传文件:', file)
      console.log('错误详情:', {
        message: error?.message,
        status: error?.status,
        statusText: error?.statusText
      })
      
      uploading.value = false
      importing.value = false
      uploadProgress.value = 0
      uploadStatus.value = 'exception'
      
      ElMessage.error('文件上传失败，请重试')
      
      importResult.value = {
        success: false,
        successSize: 0,
        errorSize: 0,
        errors: [],
        message: error?.message || '网络错误，请重试'
      }
      
      console.log('切换到错误结果页面')
      currentStep.value = 2
    }

    const removeFile = () => {
      uploadFile.value = null
      uploadProgress.value = 0
      uploadStatus.value = ''
    }

    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + ' KB'
      } else {
        return (size / 1024 / 1024).toFixed(1) + ' MB'
      }
    }

    const showErrorDetails = () => {
      errorDialogVisible.value = true
    }

    const resetImport = () => {
      console.log('=== 重置导入状态 ===')
      currentStep.value = 0
      uploadFile.value = null
      uploadProgress.value = 0
      uploadStatus.value = ''
      importResult.value = {
        success: false,
        successSize: 0,
        errorSize: 0,
        errors: [],
        message: ''
      }
    }

    // 文件变化回调
    const onFileChange = (file, fileList) => {
      console.log('=== onFileChange事件触发 ===')
      console.log('file参数:', file)
      console.log('fileList参数:', fileList)
      console.log('文件状态:', file?.status)
      
      if (file?.raw) {
        console.log('从file.raw获取文件对象')
        console.log('文件详情:', {
          name: file.raw.name,
          type: file.raw.type,
          size: file.raw.size
        })
        
        // 如果beforeUpload没有被触发（某些情况下），在这里设置uploadFile
        if (!uploadFile.value && file.raw) {
          console.log('⚠️ beforeUpload未触发，在onFileChange中设置uploadFile')
          uploadFile.value = file.raw
        }
      }
    }

    // 监听uploadFile变化
    watch(uploadFile, (newFile, oldFile) => {
      console.log('=== uploadFile状态变化 ===')
      console.log('旧文件:', oldFile)
      console.log('新文件:', newFile)
      if (newFile) {
        console.log('✅ 文件已选择，文件信息应该显示')
        console.log('文件名:', newFile.name)
        console.log('文件大小:', (newFile.size / 1024 / 1024).toFixed(2), 'MB')
      } else {
        console.log('❌ 文件被清除')
      }
    }, { immediate: true })

    return {
      // 状态
      dialogVisible,
      errorDialogVisible,
      currentStep,
      uploading,
      importing,
      downloading,
      uploadProgress,
      uploadStatus,
      uploadFile,
      importResult,
      uploadRef,
      
      // 计算属性
      dialogTitle,
      uploadAction,
      uploadHeaders,
      uploadData,
      
      // 方法
      openImportDialog,
      closeDialog,
      resetDialog,
      downloadTemplate,
      beforeUpload,
      onFileChange,
      startUpload,
      onUploadProgress,
      onUploadSuccess,
      onUploadError,
      removeFile,
      formatFileSize,
      showErrorDetails,
      resetImport
    }
  }
}
</script>

<style scoped>
.excel-import {
  display: inline-block;
}

.import-content {
  padding: 20px 0;
}

.step-indicator {
  margin-bottom: 30px;
}

.step-content {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.template-info {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-icon {
  font-size: 24px;
  color: #409eff;
  margin-right: 12px;
  margin-top: 2px;
}

.info-text h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.info-text p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.template-actions {
  text-align: center;
}

.template-actions .el-button {
  margin: 0 8px;
}

.upload-dragger {
  width: 100%;
}

.upload-content {
  padding: 40px 20px;
}

.el-icon--upload {
  color: #c0c4cc;
  margin-bottom: 16px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
  text-align: center;
}

.file-info {
  margin: 20px 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.file-item {
  display: flex;
  align-items: center;
}

.file-name {
  flex: 1;
  margin-left: 8px;
  color: #303133;
  font-size: 14px;
}

.file-size {
  color: #909399;
  font-size: 12px;
  margin-right: 8px;
}

.remove-btn {
  color: #f56c6c;
  padding: 0;
}

.upload-progress {
  margin: 20px 0;
}

.upload-actions,
.result-actions {
  text-align: center;
  margin-top: 20px;
}

.upload-actions .el-button,
.result-actions .el-button {
  margin: 0 8px;
}

.result-content {
  text-align: center;
  padding: 40px 20px;
}

.result-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.result-icon.success {
  color: #67c23a;
}

.result-icon.error {
  color: #f56c6c;
}

.success-result h4,
.error-result h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #303133;
}

.success-result p,
.error-result p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.warning-info {
  margin-top: 12px;
  color: #e6a23c;
}

/* 适配系统主题 */
.idoo-details-add {
  border-color: #714B67;
}

.idoo-details-add:hover {
  background-color: #52374b;
  border-color: #52374b;
}

.idoo-details-add:active {
  background-color: #714B67;
  border-color: #714B67;
}
</style>
